Aynı Activity içinde İki AsyncTask Arası iletişimi sağlama?
Merhabalar,
Ben geliştirdiğim uygulamada Mail Gönderme activity içerisinde kullandığım T.C Kimlik No: …….. text viewini Validate yani doğrulamak istiyorum. Bunun için sayfa activity içerisinde iki AsyncTask kullanmak zorunda kaldım biri Maili göndermek diğeride Tc kimlik sorgusunu yapıyor Geçerli yada Geçersiz olma durumunu sorguluyor. Xml kısmında ise aynı aktivity içersinde kullandığım için text viewlerin ıd lerini eşleştirdim mesela mail için ad soyad gerekirken aynı şekilde tc sorgulamak için de ad soyad gerekti ben ikisini aynı id değerinde yaparak hem gmailime kişinin ad soyadını gönderyorum hemde tc sorgulamasını yaptıryorum şimdi sorun şu ki; Ben bu activity de önce tc sorgusunun yapılmasını geçersiz yada sallamasyon bir Tc girilmişse gelen “Geçersiz Tc No” uyarısına göre mailinde gönderilmemesini istiyorum. En kısaca olaraktan doğru tc no girmemişse mailde gönderememesini istiyorum bunu nasıl yaparım?
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.Calendar;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import info.androidhive.view.Position;
import info.androidhive.view.SwipeBack;
@SuppressWarnings("ALL")
public class Dogrudanyazin extends Activity {
private static final String username = "halithatice4603@gmail.com";
private static final String password = "**********";
private EditText emailEdit;
private EditText subjectEdit;
private EditText messageEdit;
private EditText nameEdit;
private EditText surnameEdit;
private EditText tcEdit;
private EditText telEdit;
String email ;
String gonderenemail;
String name;
String surname;
String subject;
String message;
String tckn;
String tel;
String regexStr = "^[+]?[0-9]{10,13}$";
// FloatingActionButton facebook,twitter,youtube;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Activityi sağa doğru kaydırınca animasyonlu bir şekilde kapatır
SwipeBack.attach(this, Position.LEFT)
.setSwipeBackView(R.layout.swipeback_default);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dogrudanyazin);
final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
Spinner birthDateSpinner = (Spinner) findViewById(R.id.birthDateSpinner);
int startYear = Calendar.getInstance().get(Calendar.YEAR);
int endYear = 1900;
String[] birthyears = new String[startYear-endYear];
int count = 0;
for (int i = startYear; i > endYear; i--) {
birthyears[count] = Integer.toString(i);
count++;
}
ArrayAdapter adapterForBirthDate = new ArrayAdapter(this, android.R.layout.simple_spinner_item, birthyears);
adapterForBirthDate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
birthDateSpinner.setAdapter(adapterForBirthDate);
emailEdit = (EditText) findViewById(R.id.editText_eposta);
subjectEdit = (EditText)findViewById(R.id.editText_konu);
messageEdit = (EditText) findViewById(R.id.editText_ileti);
nameEdit= (EditText) findViewById(R.id.editText_isim);
surnameEdit= (EditText) findViewById(R.id.editText_soyisim);
tcEdit= (EditText) findViewById(R.id.editText_tc);
telEdit=(EditText) findViewById(R.id.editText_telno);
// Button sendButton = (Button) findViewById(R.id.button_gonder);
/* final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame);
// frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
facebook=(FloatingActionButton)findViewById(R.id.fab_face);
twitter=(FloatingActionButton)findViewById(R.id.fab_twitter);
youtube=(FloatingActionButton)findViewById(R.id.fab_youtube);
facebook.setOnClickListener(this);
twitter.setOnClickListener(this);
youtube.setOnClickListener(this);
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
@Override
public void onMenuExpanded() {
// frameLayout.getBackground().setAlpha(240);
frameLayout.setEnabled(false);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
@Override
public void onMenuCollapsed() {
// frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
EditText tcknArea = (EditText) findViewById(R.id.editText_tc);
String tckn = tcknArea.getText().toString().trim();
EditText nameArea = (EditText) findViewById(R.id.editText_isim);
String name = nameArea.getText().toString().trim();
EditText surnameArea = (EditText) findViewById(R.id.editText_soyisim);
String surname = surnameArea.getText().toString().trim();
Spinner birthDateSpinner = (Spinner) findViewById(R.id.birthDateSpinner);
String year = birthDateSpinner.getSelectedItem().toString();
if (checkInternetConnection()) {
if (name.isEmpty() || surname.isEmpty() || tckn.isEmpty()) {
Toast.makeText(Dogrudanyazin.this, "Lütfen gerekli alanları doldurunuz", Toast.LENGTH_SHORT).show();
} else {
new controlTCKNService().execute(tckn, name, surname, year);
}
} else {
Toast.makeText(Dogrudanyazin.this, "Lütfen internet bağlantınızı kontrol ediniz", Toast.LENGTH_SHORT).show();
}
email = "enhesapliburda@gmail.com";
gonderenemail = emailEdit.getText().toString();
name = nameEdit.getText().toString();
surname = surnameEdit.getText().toString();
subject = subjectEdit.getText().toString();
message = messageEdit.getText().toString();
tckn = tcEdit.getText().toString();
tel = telEdit.getText().toString();
if (!isValidEmail(gonderenemail) || gonderenemail.isEmpty() || name.isEmpty() || surname.isEmpty() || subject.isEmpty() || message.isEmpty() || tckn.isEmpty() || tel.isEmpty()) {
final String gonderenemail = emailEdit.getText().toString();
if (!isValidEmail(gonderenemail)) {
emailEdit.setError("Lütfen geçerli bir mail adresi giriniz!");
}
if (telEdit.getText().toString().length() < 10 || tel.length() > 13 || tel.matches(regexStr) == false) {
telEdit.setError("Lütfen telefon numaranızı düzgün giriniz!");
// am_checked=0;
}
Snackbar.make(arg0, "Tüm alanları doğru bir şekilde doldurunuz!", Snackbar.LENGTH_LONG).setAction("Action", null).show();
} else if (isNetworkAvailable() == false) {
Snackbar.make(arg0, "Bir hata oluştu! Lütfen internet bağlantınızı kontrol edip tekrar deneyiniz..", Snackbar.LENGTH_LONG).setAction("Action", null).show();
} else {
message = message + "\n\n\n\n" + "Gönderen e-mail: " + gonderenemail + "\n\n\n" + " Gönderen kişinin adı:" + name + "\n\n" + "Gönderen kişinin soyadı:" + surname + "\n\n" + "T.C Kimlik Numarası:" + tckn + "\n" + " Telefon Numarası:" + tel;
sendMail(email, subject, message);
nameEdit.setText("");
surnameEdit.setText("");
emailEdit.setText("");
subjectEdit.setText("");
messageEdit.setText("");
tcEdit.setText("");
telEdit.setText("");
}
}
});
}
private static final String NAMESPACE = "http://tckimlik.nvi.gov.tr/WS";
private static final String URL = "https://tckimlik.nvi.gov.tr/Service/KPSPublic.asmx?WSDL";
private static final String SOAP_ACTION = "http://tckimlik.nvi.gov.tr/WS/TCKimlikNoDogrula";
private static final String METHOD_NAME = "TCKimlikNoDogrula";
public void controlTCKN (View view) {
EditText tcknArea = (EditText) findViewById(R.id.editText_tc);
String tckn = tcknArea.getText().toString().trim();
EditText nameArea = (EditText) findViewById(R.id.editText_isim);
String name = nameArea.getText().toString().trim();
EditText surnameArea = (EditText) findViewById(R.id.editText_soyisim);
String surname = surnameArea.getText().toString().trim();
Spinner birthDateSpinner = (Spinner) findViewById(R.id.birthDateSpinner);
String year = birthDateSpinner.getSelectedItem().toString();
if(checkInternetConnection()){
if(name.isEmpty() || surname.isEmpty() || tckn.isEmpty()){
Toast.makeText(Dogrudanyazin.this,"Lütfen gerekli alanları doldurunuz", Toast.LENGTH_SHORT).show();
}else {
new controlTCKNService().execute(tckn, name, surname, year);
}
} else {
Toast.makeText(Dogrudanyazin.this,"Lütfen internet bağlantınızı kontrol ediniz", Toast.LENGTH_SHORT).show();
}
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean result = false;
// test for connection
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
result = true;
} else {
result = false;
}
return result;
}
public void clearFields (View view) {
EditText tcknArea = (EditText) findViewById(R.id.editText_tc);
EditText nameArea = (EditText) findViewById(R.id.editText_isim);
EditText surnameArea = (EditText) findViewById(R.id.editText_soyisim);
Spinner birthDateSpinner = (Spinner) findViewById(R.id.birthDateSpinner);
tcknArea.setText("");
nameArea.setText("");
surnameArea.setText("");
birthDateSpinner.setSelection(0);
}
public void aboutTCKN(View view){
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(R.string.about_app);
alertDialog.setMessage("Bu uygulama T.C. Nüfus ve Vatandaşlık İşleri Genel Müdürlüğü tarafından kullanıma sunulan web servisi üzerinden doğrulama yapmaktadır.");
alertDialog.setButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//here you can add functions
} });
alertDialog.show();
}
private class controlTCKNService extends AsyncTask<String, Void, Void> {
private String resultText;
private boolean result;
private ProgressDialog progressDialog = new ProgressDialog(Dogrudanyazin.this);
private AlertDialog.Builder builder = new AlertDialog.Builder(Dogrudanyazin.this);
AlertDialog alert;
protected void onPreExecute() {
progressDialog.setMessage("Kontrol ediliyor...");
progressDialog.show();
}
protected Void doInBackground(String... urls) {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("TCKimlikNo",urls[0]);
Request.addProperty("Ad", urls[1].toUpperCase());
Request.addProperty("Soyad", urls[2].toUpperCase());
Request.addProperty("DogumYili", urls[3]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
result = Boolean.parseBoolean( response.getProperty(0).toString());
if(result) {
resultText = getString(R.string.result_tckn_valid);
}else{
resultText = getString(R.string.result_tckn_invalid);
}
}
catch(ClassCastException e)
{
result = false;
resultText = getString(R.string.result_tckn_invalid);
}
catch(ConnectException e)
{
result = false;
resultText = getString(R.string.result_connection_error);
}
catch (UnknownHostException e) {
result = false;
resultText = getString(R.string.result_connection_error);
}
catch (UnknownServiceException e) {
result = false;
resultText = getString(R.string.result_connection_error);
}
catch(Exception e)
{
result = false;
resultText = getString(R.string.result_unknown_error)+e.toString();
}
return null;
}
protected void onPostExecute(Void unused) {
progressDialog.dismiss();
alert = builder.setMessage(resultText)
.setCancelable(true)
.setTitle("Sonuç")
.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// MyActivity.this.finish();
}
}).create();
alert.show();
}
}
// validating email id
public static boolean isValidEmail(String email) {
Pattern pattern = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+");
Matcher matcher = pattern.matcher(email);
if (matcher.matches())
{
String country_code = email.substring(email.lastIndexOf(".")+1);
if(country_code.length() >= 2)
return true;
}
return false;
}
// validating email id
/* private boolean isValidName(String name) {
String USERNAME_PATTERN = "[a-zA-Z0-9]{1,250}";
Pattern pattern = Pattern.compile(USERNAME_PATTERN);
Matcher matcher = pattern.matcher(name);
return matcher.matches();
}*/
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
javax.mail.Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private javax.mail.Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
javax.mail.Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("enhesapliburda@gmail.com", name));
message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.debug", "true");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
/* @Override
public void onClick(View v) {
switch (v.getId()){
case R.id.fab_face:
openBrowser("https://www.facebook.com/TurkcellGelecegiYazanlar");
break;
case R.id.fab_twitter:
openBrowser("https://twitter.com/GelecegiYazanlr");
break;
case R.id.fab_youtube:
openBrowser("https://www.youtube.com/channel/UCt03q1RpC8Jrifo88diQXnA");
break;
}
}
public void openBrowser(String url){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}*/
private class SendMailTask extends AsyncTask<javax.mail.Message, Void, Void> {
private String resultText;
private boolean result;
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplication(), "Mail gönderiliyor...", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplication(), "Mailiniz başarıyla gönderilmişir...", Toast.LENGTH_SHORT).show();
}
@Override
protected Void doInBackground(javax.mail.Message... messages) {
try {
Transport.send(messages[0]);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
public boolean isNetworkAvailable()
{
boolean connected = false;
ConnectivityManager connectivityManager =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()
== NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()
== NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
return connected;
}
}